package utils;

import java.util.Collections;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

import com.bean.WxConfig;
import com.google.common.collect.Lists;


/**
 * Created by tancw on 2016/10/11.
 */
public class WeixinTools {

    public static boolean access(String token, String signature, String timestamp, String nonce) {
        List<String> list = Lists.newArrayList(token, timestamp, nonce);
        Collections.sort(list);
        String str = StringUtils.join(list, "");
        return signature.equalsIgnoreCase(HashKit.sha1(str));
    }

    public static WxConfig getWxConfig(String appId, String url) {
        WxConfig wxConfig = new WxConfig(appId);
        wxConfig.setTimestamp(System.currentTimeMillis() / 1000);
        wxConfig.setNonceStr(UUID.randomUUID().toString());
        wxConfig.setSignature(sign(wxConfig, TokenUtil.getJsApiTicket(),url));
        return wxConfig;
    }

    private static String sign(WxConfig config, String jsapiTicket, String url) {
        StringBuffer sb = new StringBuffer();
        sb.append("jsapi_tocket=").append(jsapiTicket)
                .append("&noncestr=")
                .append(config.getNonceStr()).append("&timestamp=").append(config.getTimestamp())
                .append("&url=").append(url);
        return HashKit.sha1(sb.toString()).toLowerCase();

    }

}
